import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home'
import Goods from '../views/Goods'
import About from '../views/About'
import Details from '../views/Details'
import Collect from '../views/Collect'
import Shopcart from '../views/Shopcart'
import ConfimOrder from '../views/ConfimOrder'
// import fr from "element-ui/src/locale/lang/fr";

Vue.use(VueRouter)

const routes = [
    {
        path: '*',
        redirect: "/",
    },
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/goods',
        name: 'Goods',
        component: Goods
    },
    {
        path: '/about',
        name: 'About',
        component: About
    },
    {
        path: '/details',
        name: 'Details',
        component: Details
    },
    {
        path: '/collect',
        name: 'Collect',
        component: Collect,
        meta: {
            loginFlag: true
        }
    },
    {
        path: '/shopcart',
        name: 'Shopcart',
        component: Shopcart,
        meta: {
            loginFlag: true
        }
    },
    {
        path: '/confimorder',
        name: 'ConfimOrder',
        component: ConfimOrder
    },
]

//原因:在vue-router在3.1之后把 $router.push方法 改成了promise.如果没有错误捕获回调函数,错误信息就会交给全局路由进行错误处理.因此就会报错
//Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/"
// 解决方案: 禁止全局路由错误处理打印, 这个也是vue-router的开发者给出的解决方案
const originalPush = VueRouter.prototype.push
//重写原有的VueRouter.prototype.push方法
VueRouter.prototype.push = function push(location) {
    //调用call方法的原因是为了始终保持this指向,之后在原有的push方法上增加一个catch捕获
    return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
    routes
})


import store from "../store/index"

//路由守卫
router.beforeEach((to, from, next)=>{
    //如果要去的路由meta属性存在loginFlag属性 证明需要进行登录鉴权

    /*
     *
     * / if(to.meta.loginFlag && !store.getters.userInfo){
     *     store.commit("setShowLogin", true)
     *     return next(false)
     * }
     *
     * 每次刷新页面的时候vuex都会把state的user定义null,没有进行本地存储的监听
     * 通过判断本地存储是否存在user信息，来进行路由拦截并弹出dialog登录框  ， 也可以通过vuex持久化工具解决
     */



    if(to.meta.loginFlag && !window.localStorage.getItem('user')){
        //如果当前本地存储中存在user那么就表示用户登录了
        //否则就是没有登录
        //展示登录对话框
        store.commit("setShowLogin", true)
        return next(false)
    }
    next()
})

export default router
